<template>
  <div>
    <el-dialog
      title="修改用户信息"
      @close="handleClose"
      :visible.sync="dialogFormVisible"
    >
      <el-form v-model="selectedUser" style="text-align: left" ref="dataForm">
        <el-form-item label="用户名" label-width="120px" prop="username">
          <label>{{ selectedUser.username }}</label>
        </el-form-item>
        <el-form-item label="昵称" label-width="120px" prop="name">
          <el-input v-model="selectedUser.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="手机号" label-width="120px" prop="phone">
          <el-input v-model="selectedUser.phone" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" label-width="120px" prop="email">
          <el-input v-model="selectedUser.email" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="密码" label-width="120px" prop="password">
          <el-button
            type="warning"
            @click="resetPassword(selectedUser.username)"
            >重置密码</el-button
          >
          <el-input
            v-model="tempPassword"
            placeholder="请输入重置密码"
          ></el-input>
        </el-form-item>
        <el-form-item label="角色分配" label-width="120px" prop="roles">
          <el-checkbox-group v-model="selectedRolesIds">
            <el-checkbox v-for="(role, i) in roles" :key="i" :label="role.id">{{
              role.nameZh
            }}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="onSubmit(selectedUser)"
          >确 定</el-button
        >
      </div>
    </el-dialog>
    <el-row style="margin: 18px 0px 0px 18px">
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/admin/dashboard' }"
          >管理中心</el-breadcrumb-item
        >
        <el-breadcrumb-item>用户管理</el-breadcrumb-item>
        <el-breadcrumb-item>用户信息</el-breadcrumb-item>
      </el-breadcrumb>
    </el-row>
    <user-create @onSubmit="listUsers()"></user-create>
    <el-card style="margin: 18px 2%; width: 95%">
      <el-table
        ref="multipleTable"
        @selection-change="handleSelectionChange"
        :data="users"
        stripe
        :default-sort="{ prop: 'id', order: 'ascending' }"
        style="width: 100%"
        :max-height="tableHeight"
      >
        <el-table-column type="selection" width="55"> </el-table-column>
        <el-table-column prop="id" label="id" sortable width="100">
        </el-table-column>
        <el-table-column prop="username" label="用户名" fit> </el-table-column>
        <el-table-column prop="name" label="昵称" fit> </el-table-column>
        <el-table-column prop="phone" label="手机号" fit> </el-table-column>
        <el-table-column prop="email" label="邮箱" show-overflow-tooltip fit>
        </el-table-column>
        <el-table-column label="状态" sortable width="100">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.enabled"
              active-color="#13ce66"
              inactive-color="#ff4949"
              @change="(value) => commitStatusChange(value, scope.row)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120" fixed="right">
          <template slot-scope="scope">
            <el-button @click="editUser(scope.row)" type="text" size="small">
              编辑
            </el-button>
            <el-button type="text" size="small" @click="deleteUser(scope.row)">
              移除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div style="margin: 20px 0 20px 0; float: left">
        <el-button @click="toggleSelection()">取消选择</el-button>
        <el-button @click="batchDelete()">批量删除</el-button>
      </div>
    </el-card>
  </div>
</template>

<script>
import UserCreate from './UserCreate'
export default {
  name: 'UserBasic',
  components: { UserCreate },
  data () {
    return {
      users: [],
      roles: [],
      selectedUser: [],
      selectedRolesIds: [],
      dialogFormVisible: false,
      tempPassword: '',
      // 当前表格选择的记录
      multipleSelection: []
    }
  },
  mounted () {
    this.listUsers()
    this.listRoles()
  },
  computed: {
    tableHeight () {
      return window.innerHeight - 320
    }
  },
  methods: {
    listUsers () {
      var _this = this
      this.$axios.get('/admin/user/list').then((resp) => {
        if (resp && resp.status === 200) {
          _this.users = resp.data.result
        }
      })
    },
    listRoles () {
      var _this = this
      this.$axios.get('/admin/role').then((resp) => {
        if (resp && resp.status === 200) {
          _this.roles = resp.data.result
        }
      })
    },
    commitStatusChange (value, user) {
      // value为true或false
      if (user.username !== 'admin') {
        this.$axios
          .put('/admin/user/status', {
            enabled: value,
            username: user.username
          })
          .then((resp) => {
            console.log(resp.data.code)
            if (resp && resp.data.code === 200) {
              if (value) {
                this.$message('用户 [' + user.username + '] 已启用')
              } else {
                this.$message('用户 [' + user.username + '] 已禁用')
              }
            }
          })
      } else {
        user.enabled = true
        this.$alert('不能禁用管理员账户')
      }
    },
    onSubmit (user) {
      let _this = this
      // 根据视图绑定的角色 id 向后端传送角色信息
      let roleIds = []
      for (let i = 0; i < _this.selectedRolesIds.length; i++) {
        for (let j = 0; j < _this.roles.length; j++) {
          if (_this.selectedRolesIds[i] === _this.roles[j].id) {
            roleIds.push(_this.roles[j].id)
          }
        }
      }
      this.$axios
        .put('/admin/user/update', {
          user: {
            id: user.id,
            username: user.username,
            name: user.name,
            phone: user.phone,
            email: user.email,
            enabled: user.enabled
          },
          rIds: roleIds
        })
        .then((resp) => {
          if (resp && resp.data.code === 200) {
            this.$alert('用户信息修改成功')
            this.dialogFormVisible = false
            // 修改角色后重新请求用户信息，实现视图更新
            this.listUsers()
          } else {
            this.$alert(resp.data.message)
          }
        })
    },
    editUser (user) {
      this.dialogFormVisible = true
      this.selectedUser = user
      let roleIds = []
      for (let i = 0; i < user.roles.length; i++) {
        roleIds.push(user.roles[i].id)
      }
      this.selectedRolesIds = roleIds
    },
    resetPassword (username) {
      if (this.tempPassword === null || this.tempPassword === '') {
        this.$alert('密码不能为空！')
        return
      }
      this.$axios
        .put('/admin/user/password', {
          username: username,
          password: this.tempPassword
        })
        .then((resp) => {
          if (resp && resp.data.code === 200) {
            this.$alert('密码已重置为: ' + this.tempPassword)
            this.tempPassword = ''
          }
        })
    },
    // 删除用户
    deleteUser (user) {
      if (user.id !== 1) {
        this.$confirm('是否移除该用户？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            this.$axios
              .delete('/admin/user/deleteOne?username=' + user.username)
              .then((resp) => {
                if (resp && resp.data.code === 200) {
                  this.$alert('删除角色成功！')
                  // 刷新列表
                  this.listUsers()
                }
              })
          })
          .catch(() => {
            this.$message({
              type: 'info',
              message: '已取消'
            })
          })
      } else {
        this.$alert('无法移除系统管理员！')
      }
    },
    // 批量删除
    batchDelete () {
      // 获取表格已选中项的长度
      const length = this.multipleSelection.length
      if (length === 0 || length === null) {
        this.$alert('请选择至少一条数据！')
        return
      }
      // 生成含用户id的列表
      const userIds = []
      for (let i = 0; i < length; i++) {
        userIds.push(this.multipleSelection[i].id)
      }
      this.$confirm('是否批量删除选中角色？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.$axios
            .delete('/admin/user/batch', {
              data: JSON.stringify(userIds)
            })
            .then((resp) => {
              if (resp && resp.data.code === 200) {
                this.$alert('批量删除角色成功！')
                this.listUsers()
              }
            })
            .catch(() => {
              this.$alert('批量删除角色失败！')
            })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消'
          })
        })
    },
    // 实时更新选中项
    handleSelectionChange (val) {
      this.multipleSelection = val
    },
    // 取消选择
    toggleSelection (rows) {
      if (rows) {
        rows.forEach((row) => {
          this.$refs.multipleTable.toggleRowSelection(row)
        })
      } else {
        this.$refs.multipleTable.clearSelection()
      }
    },
    // 编辑取消
    cancel () {
      this.dialogFormVisible = false
      this.listUsers()
    },
    // 弹窗关闭后的回调函数，刷新列表
    handleClose () {
      this.listUsers()
    }
  }
}
</script>

<style scoped>
</style>
